<template>
  <el-button icon="UploadIcon" size="default" @click="open">{{ btnText }}</el-button>

  <vxe-modal :title="title" v-model="visible" @close="close()" width="400px">
    <el-upload
      name="files"
      action=""
      :auto-upload="false"
      :http-request="handleUpload"
      :multiple="multiple"
      ref="uploadRef"
    >
      <el-button type="primary">上传文件</el-button>
    </el-upload>
    <template #footer>
      <div>
        <el-button @click="close()">关闭</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from "vue"
import { ElMessage } from "element-plus"
import request from "@/utils/request"

const props = defineProps({
  title: {
    type: String,
    default: "上传"
  },
  btnText: {
    type: String,
    default: "上传"
  },
  multiple: {
    type: Boolean,
    default: false
  },
  params: {
    type: Object,
    default: () => ({})
  },
  action: {
    type: String,
    default: "",
    required: true
  }
})

const uploadRef = ref()
const visible = ref(false)
let fileLists: any = []
const emits = defineEmits(["asyncDownloadTemplate", "success"])

const close = () => {
  visible.value = false
}

const open = () => {
  visible.value = true
}

const handleUpload = (file: any) => {
  return fileLists.push(file)
}

const submit = async () => {
  fileLists = []

  await uploadRef.value.submit()

  const formData = new FormData()

  for (const key in props.params) {
    formData.append(key, props.params[key])
  }

  if (!fileLists.length) {
    return ElMessage.error("请先上传文件")
  }

  if (props.multiple && fileLists.length > 1) {
    return ElMessage.error("只能上传一个文件")
  }

  fileLists.forEach((file: any) => {
    formData.append("file", file.file)
  })

  request({
    url: props.action,
    method: "post",
    data: formData
  })
    .then((res) => {
      emits("success", res.data)
      ElMessage.success("上传成功")
      visible.value = false
      uploadRef.value.clearFiles()
    })
    .catch((res) => {})
}
</script>

<style lang="scss" scoped></style>
